package com.alex.tube;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

public class FeedParser {
	
	public List<Category> parseFeed(InputStream in) throws IOException {
		try {
			String feed = IOUtils.toString(in);
			String[] lines = StringUtils.split(feed, "\r");

			Map<String, Category> categories = new HashMap<String, Category>(); 

			for (String line : lines) {
				Video video = parseVideo(line.trim());
				if (video == null) {
					continue;
				}
				
				for (String categoryName : video.getCategoryNames()) {
					Category category = categories.get(categoryName);
					if (category == null) {
						category = new Category(categoryName);
						categories.put(categoryName, category);
					}
					category.getVideos().add(video);
				}
			}
			
			List<Category> result = new ArrayList<Category>(categories.values());
			for (Category category : result) {
				Collections.shuffle(category.getVideos(), new Random(1));
				category.setUrl(TubeUtils.getCategoryURL(category));
				category.setImageUrl(TubeUtils.getCategoryImageURL(category));
			}

			return result;
		} finally {
			IOUtils.closeQuietly(in);
		}
	}

	private Video parseVideo(String line) throws MalformedURLException {
		if (line.isEmpty()) {
			return null;
		}
		
		String[] parts = StringUtils.split(line, "|");
		
		if (parts.length != 5) {
			System.out.println(line);
			return null;
		}
		
		String url = parts[1];
		String title = parts[2];
		String[] categoryNames = StringUtils.split(parts[3], ",");
		URL imageUrl = new URL(parts[4]);
		
		String newImageUrl = "http://img.bankporno.info" + imageUrl.getFile();
		
		return new Video(title, url, newImageUrl, categoryNames);
	}

}
